package com.lanvideo.controller;

import com.lanvideo.entity.UserFavorite;
import com.lanvideo.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户收藏控制器
 */
@RestController
@RequestMapping("/api/favorite")
public class UserFavoriteController {

    @Autowired
    private UserFavoriteService userFavoriteService;

    /**
     * 添加收藏
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addFavorite(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            boolean success = userFavoriteService.addFavorite(userId, videoId);
            
            if (success) {
                result.put("success", true);
                result.put("message", "收藏成功");
            } else {
                result.put("success", false);
                result.put("message", "已经收藏过了");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "收藏失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 取消收藏
     */
    @PostMapping("/remove")
    public ResponseEntity<Map<String, Object>> removeFavorite(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            boolean success = userFavoriteService.removeFavorite(userId, videoId);
            
            if (success) {
                result.put("success", true);
                result.put("message", "取消收藏成功");
            } else {
                result.put("success", false);
                result.put("message", "未找到收藏记录");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "取消收藏失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 切换收藏状态
     */
    @PostMapping("/toggle")
    public ResponseEntity<Map<String, Object>> toggleFavorite(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            boolean success = userFavoriteService.toggleFavorite(userId, videoId);
            boolean isFavorited = userFavoriteService.isFavorited(userId, videoId);
            
            result.put("success", true);
            result.put("isFavorited", isFavorited);
            result.put("message", isFavorited ? "收藏成功" : "取消收藏成功");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 检查是否已收藏
     */
    @GetMapping("/check/{videoId}")
    public ResponseEntity<Map<String, Object>> checkFavorite(@PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            boolean isFavorited = userFavoriteService.isFavorited(userId, videoId);
            int favoriteCount = userFavoriteService.getVideoFavoriteCount(videoId);
            
            result.put("success", true);
            result.put("isFavorited", isFavorited);
            result.put("favoriteCount", favoriteCount);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "检查收藏状态失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户的收藏列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserFavorites(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的收藏，或者管理员可以查看所有收藏
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<UserFavorite> favorites = userFavoriteService.getUserFavorites(userId);
            result.put("success", true);
            result.put("favorites", favorites);
            result.put("count", favorites.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取收藏列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取视频的收藏数量
     */
    @GetMapping("/count/{videoId}")
    public ResponseEntity<Map<String, Object>> getVideoFavoriteCount(@PathVariable Integer videoId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            int favoriteCount = userFavoriteService.getVideoFavoriteCount(videoId);
            result.put("success", true);
            result.put("favoriteCount", favoriteCount);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取收藏数量失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 删除收藏
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteFavorite(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            boolean success = userFavoriteService.deleteFavorite(id);
            
            if (success) {
                result.put("success", true);
                result.put("message", "删除收藏成功");
            } else {
                result.put("success", false);
                result.put("message", "删除收藏失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除收藏失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
}
